#include "SQliteDataBase.h"

SQliteDataBase::SQliteDataBase():m_Db(NULL)     //对句柄进行初始化
{

}

SQliteDataBase::~SQliteDataBase()
{

}
/* 连接函数 */
bool SQliteDataBase::connectDB(const string &connStr)
{

    /* 打开数据 */
    int ret = sqlite3_open(connStr.c_str(), &m_Db);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 error" << endl;
        return false;
    }
    return true;
}
/* 执行函数 */
bool SQliteDataBase::executeSql(const string &sql)
{
    int ret = sqlite3_exec(m_Db, sql.c_str(), NULL, NULL, NULL);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 exec error" << endl;
        return false;
    }

    return true;
}
/* 查询函数 */
QueryResult SQliteDataBase::querySql(const string &sql)
{
    char ** result = NULL;
    int row = 0;
    int column = 0;

    QueryResult res;
    int ret = sqlite3_get_table(m_Db, sql.c_str(), &result, &row, &column, NULL);
    if(ret != SQLITE_OK)
    {
        std::cout << " sqlite3 get table error" << endl;
        return res;
    }

    for(int idx = 0; idx < column; idx++)
    {
        res.columnName.push_back(result[idx]);
    }

    for(int i = 0; i < row; i++)
    {
        vector<string> temp;
        for(int j = 0; j < column; j++)
        {
            temp.push_back(result[i * column + j + 2 ]);    //把每行数组数据填充
        }
        res.rows.push_back(temp);   //把每行数据填进二维数组；
    }
    return res;
}

void SQliteDataBase::close()
{
    sqlite3_close(m_Db);

}
